package com.xiaozhi.controller;

import cn.hutool.core.util.IdUtil;
import cn.hutool.system.UserInfo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.UpdateChainWrapper;
import com.xiaozhi.VO.LoginVO;
import com.xiaozhi.VO.RegisterVO;
import com.xiaozhi.entity.Discussion;
import com.xiaozhi.entity.Question;
import com.xiaozhi.entity.Student;
import com.xiaozhi.entity.Teacher;
import com.xiaozhi.service.DiscussionService;
import com.xiaozhi.service.commonService.MailService;
import com.xiaozhi.service.impl.DiscussionServiceImpl;
import com.xiaozhi.service.impl.QuestionServiceImpl;
import com.xiaozhi.service.impl.StudentServiceImpl;
import com.xiaozhi.service.impl.TeacherServiceImpl;
import com.xiaozhi.utils.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.servlet.http.HttpSession;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

/**
 * 通用请求处理
 *
 * @folder 通用请求
 */

@Api(tags = "通用请求接口")
@RestController
public class commonController {

    @Autowired
    private TeacherServiceImpl teacherService;
    @Autowired
    private StudentServiceImpl studentService;
    @Autowired
    private MailService mailService;
    @Autowired
    private TemplateEngine templateEngine;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private QuestionServiceImpl questionService;
    @Autowired
    private DiscussionService discussionService;

    /**
     * 登录接口
     *
     * @param loginVO 封装登录信息
     * @return
     */
    @ApiOperation("登录")
    @ResponseBody
    @PostMapping("/login")
    public ResponseResult<HashMap<String, Object>> login(@RequestBody LoginVO loginVO) {
        HashMap<String, Object> map = new HashMap<>();
        HashMap<String, Object> pramMap = new HashMap<>();
        pramMap.put("account", loginVO.getAccount());
        pramMap.put("password", loginVO.getPassword());
        System.out.println(loginVO);

        /*
         * 老师登录处理
         * userType: 1
         */
        if (loginVO.getUserType().equals("1")) {

            List<Teacher> teachers = teacherService.selectByAny(pramMap);
            if (teachers.size() > 0) {
                Teacher teacher = teachers.get(0);
                String token = CommonUtil.createToken("1", teacher.getAccount(), teacher.getPassword());
                map.put("token",token);
                map.put("userinfo", teacher);
                return ResponseResult.success(map);
            } else
                return ResponseResult.fail("密码错误");
        }
        /*
         * 学生登录处理
         * userType: 0
         */
        if (loginVO.getUserType().equals("0")) {

            List<Student> students = studentService.selectByAny(pramMap);
            if (students.size() > 0) {
                Student student = students.get(0);
                String token = CommonUtil.createToken("0", student.getAccount(), student.getPassword());
                map.put("token",token);
                map.put("userinfo", student);
                return ResponseResult.success(map);
            } else
                return ResponseResult.fail("密码错误");
        }

        return ResponseResult.fail("登录失败");
    }

    /**
     * 账号是否可以进行注册
     *
     * @param registerVO 注册信息
     * @return 是否可以进行注册
     */
    public boolean hasAccount(RegisterVO registerVO) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("account", registerVO.getAccount());

        //账号已存在，不能注册
        boolean flag = false;

        List<Teacher> teachers = teacherService.selectByAny(map);
        List<Student> students = studentService.selectByAny(map);
        if (teachers.size() == 0 && students.size() == 0) {
            //账号不存在，可以注册
            flag = true;
        }
        return flag;
    }

    @ApiOperation("注册")
    @ResponseBody
    @PostMapping("/register")
    public ResponseResult<HashMap<String, Object>> register(@RequestBody RegisterVO registerVO, HttpSession session){
        HashMap<String, Object> map = new HashMap<>();

        if (!hasAccount(registerVO)) {
            return ResponseResult.fail("账号已存在");
        }
        String emailCodeUser = registerVO.getEmailCode();
        String emailCodeRedis = (String) redisUtil.get("emailCode");
        System.out.println("emailCode:" + emailCodeUser);
        System.out.println("emailCodeRedis:" + emailCodeRedis);

        if (emailCodeUser == null || !emailCodeUser.equals(emailCodeRedis)) {
            return ResponseResult.fail("验证码错误");
        }

        if (registerVO.getUserType().equals("1")) {
            Teacher teacher=null;
            try {
                teacher = ChangeVO.userVO(registerVO, Teacher.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
            boolean b = teacherService.addTeacher(teacher);
            if (b) {
                return ResponseResult.success();
            } else
                return ResponseResult.fail("注册失败！");
        }
        if (registerVO.getUserType().equals("0")) {
            Student student =null;
            try {
                student=ChangeVO.userVO(registerVO,Student.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
            boolean b = studentService.addStudent(student);
            if (b) {
                return ResponseResult.success();
            } else
                return ResponseResult.fail("注册失败！");
        }
        return ResponseResult.fail("注册失败！");
    }

    /**
     * 获取用户邮箱验证码
     * @param email 用户邮箱
     */
    @ApiOperation("获取邮箱验证码")
    @ResponseBody
    @GetMapping("/getemail/{email}")
    public void getEmailCode(@PathVariable("email") String email, HttpSession session) {
        // 通过 Context 构造模版中变量需要的值
        Context ctx = new Context();
        String emailCode = com.xiaozhi.utils.emailCode.getEmailCode();

        //存入redis缓存中
        redisUtil.setex("emailCode", emailCode, 5 * 60L);
        ctx.setVariable("emailCode", emailCode);
        // 使用TemplateEngine 对模版进行渲染
        String content = templateEngine.process("mail.html", ctx);
        // 将渲染结果通过邮件发出
        mailService.sendHtmlMail("2742015729@qq.com", email, "邮箱验证", content);
    }


    @ApiOperation("通过Excel批量上传题库")
    @ResponseBody
    @PostMapping("/excel")
    public ResponseResult<HashMap<String, Object>> uploadQuestionByExcel(MultipartFile file) {
        boolean flag = false;
        try {
            Collection<Question> questions = excel.convertExcel(file);
            flag = questionService.saveBatch(questions);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (flag)
            return ResponseResult.success();
        return ResponseResult.fail("上传失败");
    }


    @ApiOperation("修改学生或老师信息")
    @PostMapping("/update")
    public ResponseResult<HashMap<String,Object>> update(@RequestBody RegisterVO registerVO){
        HashMap<String, Object> map = new HashMap<>();
        HashMap<String, Object> resMap = new HashMap<>();
        if (registerVO==null){
            return ResponseResult.fail("修改失败!");
        }
        System.out.println("update_registerVO"+registerVO);
        //获取Token信息
        LoginVO tokenInfo = CommonUtil.getTokenInfo(CommonUtil.getCurrentToken());
        System.out.println(tokenInfo);
        //老师
        if ("1".equals(tokenInfo.getUserType())){
            Teacher teacher =null;
            try {
                teacher = ChangeVO.userVO(registerVO, Teacher.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
            teacher.setAccount(tokenInfo.getAccount());
            boolean b = teacherService.update(teacher);
            if (b) {
                //修改成功，返回用户的最新信息
                map.put("account", tokenInfo.getAccount());
                List<Teacher> teachers = teacherService.selectByAny(map);
                resMap.put("userinfo",teachers.get(0));
                resMap.put("token",CommonUtil.createToken(tokenInfo.getUserType(),tokenInfo.getAccount(),registerVO.getPassword()));
                return ResponseResult.success(resMap);
            }
            else
                return ResponseResult.fail("修改失败！");
        }
        //学生
        if ("0".equals(tokenInfo.getUserType())){
            Student student=null;
            try {
                 student = ChangeVO.userVO(registerVO, Student.class);
            } catch (Exception e) {
                e.printStackTrace();
            }
            student.setAccount(tokenInfo.getAccount());
            boolean b = studentService.update(student);
            if (b){
                //修改成功，返回用户的最新信息
                map.put("account", tokenInfo.getAccount());
                List<Student> students = studentService.selectByAny(map);

                resMap.put("userinfo",students.get(0));
                resMap.put("token",CommonUtil.createToken(tokenInfo.getUserType(),tokenInfo.getAccount(),registerVO.getPassword()));
                return ResponseResult.success(resMap);
            }else
                return ResponseResult.fail("修改失败！");
        }
        return null;
    }



}
